/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.manage.biindexdatasum.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.dbs.CurrentDataSourceContext;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.common.WdAnalysisConst;
import vip.xiaonuo.modular.enums.IndexLevelEnum;
import vip.xiaonuo.modular.enums.TimeLevelEnum;
import vip.xiaonuo.modular.manage.biindexdata.entity.BiIndexData;
import vip.xiaonuo.modular.manage.biindexdata.param.BiIndexDataParam;
import vip.xiaonuo.modular.manage.biindexdata.service.BiIndexDataService;
import vip.xiaonuo.modular.manage.biindexdatasum.entity.BiIndexDataSum;
import vip.xiaonuo.modular.manage.biindexdatasum.entity.IndexDataVO;
import vip.xiaonuo.modular.manage.biindexdatasum.enums.BiIndexDataSumExceptionEnum;
import vip.xiaonuo.modular.manage.biindexdatasum.mapper.BiIndexDataSumMapper;
import vip.xiaonuo.modular.manage.biindexdatasum.param.BiIndexDataSumParam;
import vip.xiaonuo.modular.manage.biindexdatasum.param.QueryIndexParam;
import vip.xiaonuo.modular.manage.biindexdatasum.service.BiIndexDataSumService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.manage.biindextype.entity.BaseDataTitleRelevance;
import vip.xiaonuo.modular.manage.biindextype.entity.BiIndexType;
import vip.xiaonuo.modular.manage.biindextype.param.BiIndexTypeParam;
import vip.xiaonuo.modular.manage.biindextype.service.BaseDataTitleRelevanceService;
import vip.xiaonuo.modular.manage.biindextype.service.BiIndexTypeService;
import vip.xiaonuo.modular.manage.bioperateddata.entity.BiOperatedData;
import vip.xiaonuo.modular.manage.storeorder.entity.BiStoreOrder;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseDataTable;
import vip.xiaonuo.modular.manage.tsdatarecord.service.BaseDataTableService;
import vip.xiaonuo.sys.modular.area.entity.SysArea;
import vip.xiaonuo.sys.modular.area.service.SysAreaService;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 指标数据汇总service接口实现类
 *
 * @author cy
 * @date 2022-07-28 19:25:27
 */
@Service
public class BiIndexDataSumServiceImpl extends ServiceImpl<BiIndexDataSumMapper, BiIndexDataSum> implements BiIndexDataSumService {


    @Resource
    private BiIndexDataService biIndexDataService;

    @Resource
    private SysAreaService sysAreaService;

    @Resource
    private BaseDataTableService baseDataTableService;

    @Resource
    private BiIndexDataSumMapper indexDataSumMapper;

    private BiIndexTypeService indexTypeService;

    @Resource
    private BaseDataTitleRelevanceService baseDataTitleRelevanceService;
    @Override
    public PageResult<BiIndexDataSum> page(BiIndexDataSumParam biIndexDataSumParam) {
        QueryWrapper<BiIndexDataSum> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(biIndexDataSumParam)) {

            // 根据省会 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getProvName())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getProvName, biIndexDataSumParam.getProvName());
            }
            // 根据城市 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getCityName())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getCityName, biIndexDataSumParam.getCityName());
            }
            // 根据地区 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getCountryName())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getCountryName, biIndexDataSumParam.getCountryName());
            }
            // 根据类型 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getTypeId())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getTypeId, biIndexDataSumParam.getTypeId());
            }
            // 根据名称 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getName())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getName, biIndexDataSumParam.getName());
            }
            // 根据值 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getValue())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getValue, biIndexDataSumParam.getValue());
            }
            // 根据时间级别 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getTimeLevel())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getTimeLevel, biIndexDataSumParam.getTimeLevel());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getYear())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getYear, biIndexDataSumParam.getYear());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getMonth())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getMonth, biIndexDataSumParam.getMonth());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getDay())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getDay, biIndexDataSumParam.getDay());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getSeason())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getSeason, biIndexDataSumParam.getSeason());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getWeek())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getWeek, biIndexDataSumParam.getWeek());
            }
            // 根据自定义时间 查询
            if (ObjectUtil.isNotEmpty(biIndexDataSumParam.getCustomTime())) {
                queryWrapper.lambda().eq(BiIndexDataSum::getCustomTime, biIndexDataSumParam.getCustomTime());
            }

        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BiIndexDataSum> list(BiIndexDataSumParam biIndexDataSumParam) {
        return this.list();
    }

    @Override
    public void add(BiIndexDataSumParam biIndexDataSumParam) {
        BiIndexDataSum biIndexDataSum = new BiIndexDataSum();
        BeanUtil.copyProperties(biIndexDataSumParam, biIndexDataSum);
        this.save(biIndexDataSum);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BiIndexDataSumParam> biIndexDataSumParamList) {
        biIndexDataSumParamList.forEach(biIndexDataSumParam -> {
            this.removeById(biIndexDataSumParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BiIndexDataSumParam biIndexDataSumParam) {
        BiIndexDataSum biIndexDataSum = this.queryBiIndexDataSum(biIndexDataSumParam);
        BeanUtil.copyProperties(biIndexDataSumParam, biIndexDataSum);
        this.updateById(biIndexDataSum);
    }

    @Override
    public BiIndexDataSum detail(BiIndexDataSumParam biIndexDataSumParam) {
        return this.queryBiIndexDataSum(biIndexDataSumParam);
    }

    /**
     * 获取指标数据汇总
     *
     * @author cy
     * @date 2022-07-28 19:25:27
     */
    private BiIndexDataSum queryBiIndexDataSum(BiIndexDataSumParam biIndexDataSumParam) {
        BiIndexDataSum biIndexDataSum = this.getById(biIndexDataSumParam.getId());
        if (ObjectUtil.isNull(biIndexDataSum)) {
            throw new ServiceException(BiIndexDataSumExceptionEnum.NOT_EXIST);
        }
        return biIndexDataSum;
    }

    @Override
    public void export(BiIndexDataSumParam biIndexDataSumParam) {
        List<BiIndexDataSum> list = this.list(biIndexDataSumParam);
        PoiUtil.exportExcelWithStream("SnowyBiIndexDataSum.xls", BiIndexDataSum.class, list);
    }

    @Override
    public List findAllProvince() {
        return null;
    }


    @Override
    public List<BiIndexDataSum> indexDataList(BiIndexDataSumParam dataSumParam) {
        LambdaQueryWrapper<BiIndexDataSum> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BiIndexDataSum::getTypeId,dataSumParam.getTypeId());
        //指标层级
        if(StringUtils.isNotEmpty(dataSumParam.getProvName())){
            wrapper.eq(BiIndexDataSum::getProvName,dataSumParam.getProvName());
        }
        if(StringUtils.isNotEmpty(dataSumParam.getCityName())){
            wrapper.eq(BiIndexDataSum::getCityName,dataSumParam.getCityName());
        }
        if(StringUtils.isNotEmpty(dataSumParam.getCountryName())){
            wrapper.eq(BiIndexDataSum::getCountryName,dataSumParam.getCountryName());
        }

        //指标时间级别
        if(TimeLevelEnum.YEAR.getCode()==dataSumParam.getTimeLevel()){
            wrapper.eq(BiIndexDataSum::getYear,dataSumParam.getYear());
        }
        if(TimeLevelEnum.MONTH.getCode()==dataSumParam.getTimeLevel()){
            wrapper.eq(BiIndexDataSum::getMonth,dataSumParam.getMonth());
        }
        if(TimeLevelEnum.DAY.getCode()==dataSumParam.getTimeLevel()){
            wrapper.eq(BiIndexDataSum::getDay,dataSumParam.getDay());
        }
        if(TimeLevelEnum.SEASON.getCode()==dataSumParam.getTimeLevel()){
            wrapper.eq(BiIndexDataSum::getSeason,dataSumParam.getSeason());
        }
        if(TimeLevelEnum.WEEK.getCode()==dataSumParam.getTimeLevel()){
            wrapper.eq(BiIndexDataSum::getWeek,dataSumParam.getWeek());
        }
        return this.getBaseMapper().selectList(wrapper);
    }


    @Override
    public void dataSum(Long id) {
        List<BiIndexData> biIndexDataList = biIndexDataService.findByRecordId(id.toString());
        List<BaseDataTable> baseDataTables = baseDataTableService.findListByRecordId(id);
        List<Long> ids = new ArrayList<>();
        for (BaseDataTable baseDataTable : baseDataTables) {
            ids.add(baseDataTable.getId());
        }
        List<BaseDataTitleRelevance> baseDataTitleRelevances = baseDataTitleRelevanceService.findByIds(ids);
        for (BaseDataTable baseDataTable : baseDataTables) {
            for (BaseDataTitleRelevance baseDataTitleRelevance : baseDataTitleRelevances) {
                if (baseDataTable.getId().compareTo(baseDataTitleRelevance.getTableId())==0){
                    baseDataTable.setTitle(baseDataTitleRelevance.getRelevanceName());
                    baseDataTable.setTypeId(baseDataTitleRelevance.getIndexTypeId());
                }
            }
        }

        Set<String> citySet = new HashSet<>();
        Set<String> counSet= new HashSet<>();
        for (BiIndexData biIndexData : biIndexDataList) {
            citySet.add(biIndexData.getCityName());
            counSet.add(biIndexData.getCountryName());
        }

        //        省份汇总
        for (BaseDataTable baseDataTable : baseDataTables) {
            if (baseDataTable.getDataIndex().equals("index1")
                    || baseDataTable.getDataIndex().equals("index2")
                    || baseDataTable.getDataIndex().equals("index3")) {
                continue;
            }
            BiIndexDataSum biIndexDataSumProv = new BiIndexDataSum();
            for (BiIndexData biIndexData : biIndexDataList) {
                if (baseDataTable.getTypeId().compareTo(biIndexData.getTypeId()) == 0) {
                    BeanUtils.copyProperties(biIndexData, biIndexDataSumProv);
                    biIndexDataSumProv.setTypeId(biIndexData.getTypeId());
                    biIndexDataSumProv.setName(biIndexData.getName());
                    biIndexDataSumProv.setValue(new BigDecimal(biIndexData.getValue()).add(new BigDecimal(biIndexData.getValue())));
                    biIndexDataSumProv.setCityName("");
                    biIndexDataSumProv.setCountryName("");
                }
            }
            this.save(biIndexDataSumProv);
        }
//        //        城市汇总
//        for (String cityName : citySet) {
//            for (BaseDataTable baseDataTable : baseDataTables) {
//                if (baseDataTable.getDataIndex().equals("index1")
//                    || baseDataTable.getDataIndex().equals("index2")
//                    || baseDataTable.getDataIndex().equals("index3")) {
//                continue;
//            }
//                BiIndexDataSum biIndexDataSumCity = new BiIndexDataSum();
//                for (BiIndexData biIndexData : biIndexDataList) {
//                    if (baseDataTable.getTypeId().compareTo(biIndexData.getTypeId()) == 0
//                            && cityName.equals(biIndexData.getCityName())) {
//                        BeanUtils.copyProperties(biIndexData, biIndexDataSumCity);
//                        biIndexDataSumCity.setTypeId(biIndexData.getTypeId());
//                        biIndexDataSumCity.setName(biIndexData.getName());
//                        biIndexDataSumCity.setValue(new BigDecimal(biIndexData.getValue()).add(new BigDecimal(biIndexData.getValue())));
//                        biIndexDataSumCity.setCityName(cityName);
//                        biIndexDataSumCity.setCountryName("");
//                    }
//                }
//                this.save(biIndexDataSumCity);
//            }
//        }
//        //        区/县汇总
//        for (String counName : counSet) {
//            for (BaseDataTable baseDataTable : baseDataTables) {
//                if (baseDataTable.getDataIndex().equals("index1")
//                        || baseDataTable.getDataIndex().equals("index2")
//                        || baseDataTable.getDataIndex().equals("index3")) {
//                    continue;
//                }
//                BiIndexDataSum biIndexDataSumCoun = new BiIndexDataSum();
//                for (BiIndexData biIndexData : biIndexDataList) {
//                    if (baseDataTable.getTypeId().compareTo(biIndexData.getTypeId()) == 0
//                        && counName.equals(biIndexData.getCountryName())) {
//                        BeanUtils.copyProperties(biIndexData, biIndexDataSumCoun);
//                        biIndexDataSumCoun.setTypeId(biIndexData.getTypeId());
//                        biIndexDataSumCoun.setName(biIndexData.getName());
//                        biIndexDataSumCoun.setValue(new BigDecimal(biIndexData.getValue()).add(new BigDecimal(biIndexData.getValue())));
//                        biIndexDataSumCoun.setCountryName(counName);
//                    }
//                }
//                this.save(biIndexDataSumCoun);
//            }
//        }
    }

    @Override
    public void upload(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            Reader reader = new BufferedReader(inputStreamReader);

            String[] headers = {
                    "prov_name", "city_name", "time_level", "year", "type_id", "name", "value"
            };
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader(headers).withSkipHeaderRecord().parse(reader);
            List<BiIndexDataSum> list = new ArrayList<>();
            for (CSVRecord record : records) {
                if (StringUtils.isBlank(record.get("prov_name"))) {
                    break ;
                }
                BiIndexDataSum indexData = new BiIndexDataSum();
                indexData.setProvName(record.get("prov_name"));
                indexData.setCityName(record.get("city_name"));
                indexData.setName(record.get("name"));

                String value = record.get("value");
                if (StringUtils.isNotEmpty(value)) {
                    String recordValue = value.trim();
                    BigDecimal indexValue = new BigDecimal(recordValue);
                    indexData.setValue(indexValue);
                } else {
                    indexData.setValue(new BigDecimal(0));
                }

                String typeId = record.get("type_id");
                if (StringUtils.isNotEmpty(typeId)) {
                    indexData.setTypeId(Long.valueOf(typeId));
                }

                indexData.setYear(Integer.valueOf(record.get("year")));
                indexData.setTimeLevel(Integer.valueOf(record.get("time_level")));
                list.add(indexData);
            }
            this.saveBatch(list, 1000);
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<BiIndexDataSum> findIndexDataListByParams(QueryIndexParam dataSumParam) {
        LambdaQueryWrapper<BiIndexDataSum> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dataSumParam.getCityName())) {
            wrapper.eq(BiIndexDataSum::getCityName, dataSumParam.getCityName());
        }
        if (dataSumParam.getYear() != null && dataSumParam.getYear() > 0) {
            wrapper.eq(BiIndexDataSum::getYear, dataSumParam.getYear());
        }

        // TypeId 不能为空
        if (dataSumParam.getTypeId() != null && dataSumParam.getTypeId() > 0) {
            wrapper.eq(BiIndexDataSum::getTypeId, dataSumParam.getTypeId());
        }
        wrapper.orderByAsc(BiIndexDataSum::getYear);
        return this.getBaseMapper().selectList(wrapper);
    }

    @Override
    public List<BiIndexDataSum> findLastListByYearAndNum(QueryIndexParam param) {
        LambdaQueryWrapper<BiIndexDataSum> wrapper = new LambdaQueryWrapper<>();
        if (param.getYear() != null && param.getYear() > 0) {
            wrapper.eq(BiIndexDataSum::getYear, param.getYear());
        }
        // TypeId 不能为空
        if (param.getTypeId() != null && param.getTypeId() > 0) {
            wrapper.eq(BiIndexDataSum::getTypeId, param.getTypeId());
        }

        wrapper.orderByDesc(BiIndexDataSum::getValue);
        if (param.getNum() != null && param.getNum() > 0) {
            wrapper.last(" limit 0, " + param.getNum());
        }

        return this.getBaseMapper().selectList(wrapper);
    }

    @Override
    public BiIndexDataSum findIndexDataByCityNameAndYear(BiIndexDataSumParam dataSumParam) {
        LambdaQueryWrapper<BiIndexDataSum> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotEmpty(dataSumParam.getCityName())) {
            wrapper.eq(BiIndexDataSum::getCityName, dataSumParam.getCityName());
        }
        if (dataSumParam.getYear() != null && dataSumParam.getYear() > 0) {
            wrapper.eq(BiIndexDataSum::getYear, dataSumParam.getYear());
        }

        // TypeId 不能为空
        if (dataSumParam.getTypeId() != null && dataSumParam.getTypeId() > 0) {
            wrapper.eq(BiIndexDataSum::getTypeId, dataSumParam.getTypeId());
        }
        return this.getBaseMapper().selectOne(wrapper);
    }

    @Override
    public JSONObject findDefaultIndexData(QueryIndexParam param) {
        String cityName = param.getCityName();
        if (StringUtils.isBlank(cityName)) {
            param.setCityName("广州市");
        }

        if (param.getYear() == null || param.getYear() == 0) {
            param.setYear(2021);
        }

        JSONObject object = findRankList(param);
        // 汇总数据
        List<IndexDataVO> defaultDataList = indexDataSumMapper.findBusinessIndexList("'" + param.getCityName()+"'", param.getYear());
        if (defaultDataList != null && defaultDataList.size() > 0) {
            object.put("defaultData", defaultDataList.get(0));
        }
        
        QueryIndexParam indexParam = new QueryIndexParam();
        indexParam.setTypeId(1676624971729813506L);
        indexParam.setCityName(param.getCityName());
        List<BiIndexDataSum> indexTrendList = this.findIndexDataListByParams(indexParam);
        if (indexTrendList != null && indexTrendList.size() > 0) {
            object.put("indexTrendList", indexTrendList);
        }
        return object;
    }

    @Override
    public JSONObject findRankList(QueryIndexParam param) {
        String cityName = param.getCityName();
        if (StringUtils.isBlank(cityName)) {
            param.setCityName("广州市");
        }

        if (param.getYear() == null || param.getYear() == 0) {
            param.setYear(2021);
        }
        if (param.getNum() == null || param.getNum() == 0) {
            param.setNum(5);
        }

        param.setTypeId(1676624971729813506L);
        // 指数排行城市
        List<BiIndexDataSum> rankList = findLastListByYearAndNum(param);
        StringBuilder sb = new StringBuilder();
        rankList.forEach(indexData -> {
            sb.append("'");
            sb.append(indexData.getCityName());
            sb.append("'").append(",");
        });
        String cityNameValue = sb.substring(0, sb.length() - 1);
        List<IndexDataVO> defaultRankList = indexDataSumMapper.findRankList(cityNameValue, param.getYear());
        List<IndexDataVO> defaultTrendList = indexDataSumMapper.findBusinessIndexList(cityNameValue, param.getYear());
        JSONObject object = new JSONObject();
        object.put("defaultRankList", defaultRankList);
        object.put("defaultTrendList", defaultTrendList);
        return object;
    }

    @Override
    public JSONObject findTrendList(BiIndexDataSumParam dataSumParam) {
        if (StringUtils.isBlank(dataSumParam.getCityName())) {
            dataSumParam.setCityName("北京市");
        }

        if (dataSumParam.getYear() == null || dataSumParam.getYear() == 0) {
            dataSumParam.setYear(2021);
        }
        String cityNameValue = "'" + dataSumParam.getCityName() + "'";
        List<IndexDataVO> defaultTrendList = indexDataSumMapper.findBusinessIndexList(cityNameValue, dataSumParam.getYear());
        JSONObject object = new JSONObject();
        object.put("defaultTrendList", defaultTrendList);
        return object;
    }

    @Override
    public JSONObject findIndexDetailList(QueryIndexParam param) {
        JSONObject object = new JSONObject();
//        if (param.getTypeId() != null || param.getTypeId() == 0) {
//            param.setTypeId(1670637266550145026L);
//        }
        // 三级指标数据
        List<BiIndexDataSum> subIndexList = indexDataSumMapper.findSubIndexList(param.getCityName(),
                param.getYear(), param.getTypeId());
        if (subIndexList != null && subIndexList.size() > 0) {
            object.put("subIndexList", subIndexList);
        }

        subIndexList.forEach(indexData -> {
            param.setTypeId(indexData.getTypeId());
            switch (indexData.getName()) {
                case "融资水平":
                    object.put("financeList", findIndexDataListByParams(param));
                    break;
                case "研发投入":
                    object.put("devInvestList", findIndexDataListByParams(param));
                    break;
                case "企业品牌设立":
                    object.put("brandList", findIndexDataListByParams(param));
                    break;
                case "创业企业数量":
                    object.put("corpList", findIndexDataListByParams(param));
                    break;
                case "非公有经济比重":
                    object.put("nonPublicEconList", findIndexDataListByParams(param));
                    break;
                case "水价":
                    object.put("waterPriceList", findIndexDataListByParams(param));
                    break;
                case "地价":
                    object.put("landPriceList", findIndexDataListByParams(param));
                    break;
                case "人力资本":
                    object.put("humanCapitalList", findIndexDataListByParams(param));
                    break;
                case "网络":
                    object.put("networkList", findIndexDataListByParams(param));
                    break;
                default:
                    break;
            }
        });
        List<IndexDataVO> defaultDataList = indexDataSumMapper.findBusinessIndexList("'" + param.getCityName()+"'", param.getYear());
        if (defaultDataList != null && defaultDataList.size() > 0) {
            object.put("subIndexData", defaultDataList.get(0));
        }

        return object;
    }

    @Override
    public JSONObject findIndexDetailData(QueryIndexParam indexParam) {
        if (StringUtils.isBlank(indexParam.getCityName())) {
            indexParam.setCityName("广州市");
        }

        if (indexParam.getYear() == null || indexParam.getYear() == 0) {
            indexParam.setYear(2021);
        }

        // 汇总数据
        List<IndexDataVO> defaultDataList = indexDataSumMapper.findBusinessIndexList("'" + indexParam.getCityName()+"'", indexParam.getYear());
        List<BiIndexDataSum> subIndexList = indexDataSumMapper.findSubIndexList(indexParam.getCityName(),
                indexParam.getYear(), indexParam.getTypeId());

        JSONObject object = new JSONObject();
        object.put("defaultData", defaultDataList.get(0));
        object.put("subIndexList", subIndexList);
        return object;
    }

    @Override
    public JSONObject findAllIndexData(QueryIndexParam param) {

        JSONObject object = findSecondIndexData(param);

        // 获取一级指标数据
        List<IndexDataVO> firstIndexDataList = indexDataSumMapper.findBusinessIndexList("'" + param.getCityName()+"'", param.getYear());
        if (firstIndexDataList != null && firstIndexDataList.size() > 0) {
            object.put("firstIndexData", firstIndexDataList.get(0));
        }
        return object;
    }

    @Override
    public JSONObject findSecondIndexData(QueryIndexParam param) {
        JSONObject object = new JSONObject();
        // 初始进入详细分析页面
        if (param.getTypeId() == null || param.getTypeId() == 0) {
            param.setTypeId(1670637266550145026L);
        }

        // 二级指标
        List<BiIndexDataSum> secondIndexList = indexDataSumMapper.findSecondIndexList(param.getCityName(),
                param.getYear(), param.getTypeId());
        if (secondIndexList != null && secondIndexList.size() > 0) {
            object.put("secondIndexList", secondIndexList);

            // 二级指标趋势
            BiIndexDataSum secondIndex = secondIndexList.get(0);
            QueryIndexParam secondIndexParam = new QueryIndexParam();
            secondIndexParam.setTypeId(secondIndex.getTypeId());
            secondIndexParam.setCityName(param.getCityName());
            List<BiIndexDataSum> secondIndexTrendList = findIndexDataListByParams(secondIndexParam);
            object.put("secondIndexTrendList", secondIndexTrendList);

            // 二级指标对应的三级指标
            List<BiIndexDataSum> thirdIndexList = indexDataSumMapper.findSecondIndexList(param.getCityName(),
                    param.getYear(), secondIndex.getTypeId());
            object.put("thirdIndexList", thirdIndexList);
        }
        return object;
    }
    @Override
    public JSONObject findThirdIndexData(QueryIndexParam param) {
        JSONObject object = new JSONObject();
        QueryIndexParam secondIndexParam = new QueryIndexParam();
        secondIndexParam.setTypeId(param.getTypeId());
        secondIndexParam.setCityName(param.getCityName());
        List<BiIndexDataSum> secondIndexTrendList = findIndexDataListByParams(secondIndexParam);
        object.put("secondIndexTrendList", secondIndexTrendList);
        // 二级指标对应的三级指标
        List<BiIndexDataSum> thirdIndexList = indexDataSumMapper.findSecondIndexList(param.getCityName(),
                param.getYear(), param.getTypeId());
        object.put("thirdIndexList", thirdIndexList);
        return object;
    }
}
